<?php


namespace NanQi\Hope\Di;

use Swoole\Process;
use Hyperf\Utils\Coroutine;
use Hyperf\Utils\Filesystem\FileNotFoundException;

class Watcher extends \Hyperf\Watcher\Watcher
{
    /**
     * @param bool $isStart
     * @throws FileNotFoundException
     */
    public function restart($isStart = true)
    {
        $file = $this->config->get('server.settings.pid_file');
        if (empty($file)) {
            throw new FileNotFoundException('The config of pid_file is not found.');
        }
        if (! $isStart && $this->filesystem->exists($file)) {
            $pid = $this->filesystem->get($file);
            try {
                $this->output->writeln('Stop server...');
                if (Process::kill((int) $pid, 0)) {
                    Process::kill((int) $pid, SIGTERM);
                }
            } catch (\Throwable $exception) {
                $this->output->writeln('Stop server failed. Please execute `composer dump-autoload -o`');
            }
        }

        Coroutine::create(function () {
            $this->channel->pop();
            $this->output->writeln('Start server ...');

            $descriptorspec = [
                0 => STDIN,
                1 => STDOUT,
                2 => STDERR,
            ];

            proc_open('vendor/bin/hope-bootstrap start', $descriptorspec, $pipes, null, ["IS_WATCH" => '1']);

            $this->output->writeln('Stop server success.');
            $this->channel->push(1);
        });
    }
}